import 'dart:io';
import 'dart:typed_data';

import 'package:shortmovieapp/common.dart';
import 'package:shortmovieapp/http/core/http_error.dart';

import 'http_adapter.dart';
import 'http_response.dart';

enum HttpMethod{
  Get,
  Post,
  Delete,
}

class HttpRequest{
  Map<String,dynamic> params = {};
  Map<String,dynamic> headers = {};
  late String url;
  late  HttpMethod httpMethod;
  HttpAdapter? adapter;
  late String contentType;

  HttpRequest();

  HttpRequest.init(this.adapter,this.url,this.httpMethod,
  {this.contentType = "application/json"});
 
  HttpRequest.initOctetSteam(this.adapter,this.url,this.httpMethod,
  {this.contentType = "application/octet-stream"});

  void addParam(String key,Object value){
    params[key] = value.toString();
  }
  void addHeader(String key,Object value){
    headers[key] = value.toString();
  }

  String getParamString(){
    String paramStr = "";
    for (var pair in params.entries)
    {
        if (paramStr.isEmpty)
            paramStr = "?${pair.key}=${pair.value}";
        else
            paramStr += "&${pair.key}=${pair.value}";
    }
    return paramStr;
  }

  String getUrlWithParams(){
      return url + getParamString();
  }
  Future<HttpResponse> send() async{
    //Debug.log("send request, url:$url");
    if(adapter == null) {
      return Future<HttpResponse>.error("adater hasn't been initialized");
    }
    HttpResponse response;
    try{
        return adapter!.send(this);
    }
    catch(e){
      Debug.log("request error:${e.toString()}");
      response = HttpResponse(code: -1, message: e.toString(),request: this);
      return response;
    }
  }
  Future<HttpResponse> sendFile(String file) async{
    //Debug.log("send request, url:$url");
    if(adapter == null) {
      return Future<HttpResponse>.error("adater hasn't been initialized");
    }
    HttpResponse response;
    try{
        return adapter!.sendFile(this,file);
    }
    catch(e){
      Debug.log("request error:${e.toString()}");
      response = HttpResponse(code: -1, message: e.toString(),request: this);
      return response;
    }
  }
}
